import request from '@/api/request'
import type { ApiResponse, PageResponse } from '@/types/api'
import type { ShareInfo, ShareStats } from '@/types/share'

// 分享相关的类型定义
export interface CreateShareRequest {
  fileId: number
  shareType: 'PUBLIC' | 'PASSWORD'
  password?: string
  allowDownload?: boolean
  allowPreview?: boolean
  expireTime?: string
  maxAccessCount?: number
  description?: string  // 分享备注
}

export interface ShareResponse {
  id: number
  shareCode: string
  shareUrl: string
  fileId: number
  fileName: string
  fileSize?: number
  userId: number
  userName?: string
  shareType: 'PUBLIC' | 'PASSWORD'
  allowDownload: boolean
  allowPreview: boolean
  expireTime?: string
  accessCount: number
  maxAccessCount?: number
  status: 'ACTIVE' | 'DISABLED' | 'EXPIRED'
  createdAt: string
  updatedAt: string
  expired: boolean
  available: boolean
  description?: string  // 分享备注
}

export interface ShareListResponse {
  content: ShareResponse[]
  totalElements: number
  totalPages: number
  currentPage: number
}

export interface ShareAccessRequest {
  password?: string
  action?: 'VIEW' | 'DOWNLOAD'
}

export interface ShareAccessResponse {
  allowed: boolean
  accessToken?: string
  previewUrl?: string
  downloadUrl?: string
  permissions?: {
    allowPreview: boolean
    allowDownload: boolean
  }
  fileInfo?: {
    fileId: number
    fileName: string
    fileSize: number
    mimeType: string
    sharerName: string
  }
  errorMessage?: string
}

export interface ShareInfoResponse {
  shareCode: string
  fileName: string
  fileSize: number
  shareType: 'PUBLIC' | 'PASSWORD'
  allowPreview: boolean
  allowDownload: boolean
  sharerName: string
  expired: boolean
}

export interface ShareStatsResponse {
  totalShares: number
  activeShares: number
  totalViews: number
  todayViews: number
}

export interface UpdateShareParams {
  shareType: 'PUBLIC' | 'PASSWORD'
  password?: string
  expireTime?: string
  maxAccessCount?: number
  allowDownload: boolean
  allowPreview: boolean
}

/**
 * 创建文件分享
 */
export const createShare = (data: CreateShareRequest) => {
  return request.post<ShareResponse>('/shares', data)
}

/**
 * 获取用户分享列表
 */
export const getShareList = (params: any) => {
  return request.get<ApiResponse<PageResponse<ShareInfo>>>('/shares', { params })
}

/**
 * 更新分享设置
 */
export const updateShare = (id: number, data: UpdateShareParams) => {
  return request.put<ApiResponse<ShareInfo>>(`/shares/${id}`, data)
}

/**
 * 删除分享
 */
export const deleteShare = (id: number) => {
  return request.delete<ApiResponse<void>>(`/shares/${id}`)
}

/**
 * 获取分享统计
 */
export const getShareStats = () => {
  return request.get<ApiResponse<ShareStats>>('/shares/stats')
}

/**
 * 获取分享信息 (公开接口，无需登录)
 */
export const getShareInfo = (shareCode: string) => {
  return request.get<ShareInfoResponse>(`/shares/${shareCode}/info`)
}

/**
 * 访问分享文件 (公开接口，无需登录)
 */
export const accessShare = (shareCode: string, data: ShareAccessRequest) => {
  return request.post<ShareAccessResponse>(`/shares/${shareCode}/access`, data)
}

/**
 * 下载分享文件
 */
export const downloadSharedFile = (shareCode: string, token: string) => {
  const url = `/shares/${shareCode}/download?token=${token}`
  return request.get(url, { responseType: 'blob' })
}

/**
 * 预览分享文件
 */
export const previewSharedFile = (shareCode: string, token: string) => {
  const url = `/shares/${shareCode}/preview?token=${token}`
  return request.get(url, { responseType: 'blob' })
}

/**
 * 复制分享链接到剪贴板
 */
export const copyShareLink = async (shareUrl: string): Promise<boolean> => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(shareUrl)
      return true
    } else {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = shareUrl
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      const result = document.execCommand('copy')
      textArea.remove()
      return result
    }
  } catch (error) {
    console.error('复制失败:', error)
    return false
  }
}

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 格式化时间
 */
export const formatTime = (timeString: string): string => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

export const disableShare = (id: number) => {
  return request.put<ApiResponse<void>>(`/shares/${id}/disable`)
}

export const enableShare = (id: number) => {
  return request.put<ApiResponse<void>>(`/shares/${id}/enable`)
}

/**
 * 获取分享访问日志
 */
export const getShareAccessLogs = (id: number, params?: any) => {
  return request.get<ApiResponse<PageResponse<any>>>(`/shares/${id}/logs`, { params })
}
